<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="场景名称" prop="sceneName">
        <el-input v-model="form.sceneName" placeholder="请输入场景名称" />
      </el-form-item>

      <el-form-item label="触发方式" prop="triggerMode">
        <el-select v-model="form.triggerMode" placeholder="请选择触发方式">
          <el-option label="设备触发" value="device" />
          <el-option label="定时触发" value="timer" />
          <el-option label="手动触发" value="manual" />
        </el-select>
      </el-form-item>

      <!-- 设备触发配置 -->
      <template v-if="form.triggerMode === 'device'">
        <el-form-item label="触发设备" prop="deviceId">
          <el-row :gutter="10">
            <el-col :span="8">
              <el-select v-model="form.triggerType" placeholder="请选择触发类型" @change="handleTriggerTypeChange">
                <el-option label="设备触发" value="device" />
                <el-option label="产品触发" value="product" />
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-input-number 
                v-model="form.deviceCount" 
                :min="1" 
                :max="10"
                placeholder="数量"
              />
            </el-col>
            <el-col :span="8">
              <el-button type="primary" @click="handleSelectDevice">选择设备</el-button>
            </el-col>
          </el-row>
        </el-form-item>

        <!-- 设备物模型选择 -->
        <template v-if="form.selectedDevices && form.selectedDevices.length > 0">
          <el-form-item 
            v-for="(device, index) in form.selectedDevices" 
            :key="device.id || device.deviceId"
            :label="'设备' + (index + 1)"
          >
            <el-row>
              <el-col :span="8">
                <span>{{ device.deviceName }}</span>
              </el-col>
              <el-col :span="16">
                <model-select 
                  :ref="'modelSelect' + index"
                  :deviceId="Number(device.deviceId || device.id)"
                  @change="(val) => handleModelChange(val, index)"
                />
              </el-col>
            </el-row>
          </el-form-item>
        </template>

        <!-- 产品物模型选择 -->
        <template v-if="form.selectedProducts && form.selectedProducts.length > 0">
          <el-form-item 
            v-for="(product, index) in form.selectedProducts" 
            :key="product.id || product.productId"
            :label="'产品' + (index + 1)"
          >
            <el-row>
              <el-col :span="8">
                <span>{{ product.productName }}</span>
              </el-col>
              <el-col :span="16">
                <model-select 
                  :ref="'modelSelect' + index"
                  :productId="Number(product.productId || product.id)"
                  @change="(val) => handleModelChange(val, index)"
                />
              </el-col>
            </el-row>
          </el-form-item>
        </template>
      </template>

      <!-- 定时触发配置 -->
      <template v-if="form.triggerMode === 'timer'">
        <el-form-item label="定时规则" prop="cronExpression">
          <el-input v-model="form.cronExpression" placeholder="请输入Cron表达式" />
        </el-form-item>
      </template>

      <el-form-item>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </el-form-item>
    </el-form>

    <!-- 设备选择对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="deviceDialogVisible" width="800px" append-to-body>
      <el-table v-loading="loading" :data="deviceList" @selection-change="handleDeviceSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="设备名称" align="center" prop="deviceName" />
        <el-table-column label="设备编号" align="center" prop="deviceCode" />
        <el-table-column label="产品名称" align="center" prop="productName" />
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.iot_device_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getDeviceList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmSelectDevice">确 定</el-button>
        <el-button @click="deviceDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ModelSelect from './components/ModelSelect';
import { listDevice } from "@/api/iot/device";

export default {
  name: "SceneForm",
  components: {
    ModelSelect
  },
  dicts: ['iot_device_status'],
  data() {
    return {
      // 表单参数
      form: {
        sceneName: '',
        triggerMode: 'device',
        triggerType: 'device',
        deviceCount: 1,
        selectedDevices: [],
        selectedProducts: [],
        cronExpression: '',
        modelConfigs: []
      },
      // 表单校验
      rules: {
        sceneName: [
          { required: true, message: "场景名称不能为空", trigger: "blur" }
        ],
        triggerMode: [
          { required: true, message: "触发方式不能为空", trigger: "change" }
        ]
      },
      // 设备选择对话框
      deviceDialogVisible: false,
      dialogTitle: '',
      loading: false,
      // 遮罩层
      total: 0,
      // 设备列表
      deviceList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceName: null,
        deviceCode: null,
        status: null
      },
      // 选中的设备
      selectedDevices: []
    };
  },
  methods: {
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // TODO: 提交表单
        }
      });
    },
    // 取消按钮
    cancel() {
      this.$router.push({ path: "/iot/scene" });
    },
    // 处理触发类型变化
    handleTriggerTypeChange(val) {
      this.form.selectedDevices = [];
      this.form.selectedProducts = [];
      this.form.modelConfigs = [];
    },
    // 处理选择设备按钮
    handleSelectDevice() {
      this.deviceDialogVisible = true;
      this.dialogTitle = this.form.triggerType === 'device' ? '选择设备' : '选择产品';
      this.getDeviceList();
    },
    // 获取设备列表
    getDeviceList() {
      this.loading = true;
      listDevice(this.queryParams).then(response => {
        this.deviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 处理设备选择变化
    handleDeviceSelectionChange(selection) {
      this.selectedDevices = selection;
    },
    // 确认设备选择
    confirmSelectDevice() {
      console.log('Selected devices:', this.selectedDevices);
      if (this.selectedDevices.length !== this.form.deviceCount) {
        this.$modal.msgError(`请选择${this.form.deviceCount}个${this.form.triggerType === 'device' ? '设备' : '产品'}`);
        return;
      }

      // 清空之前的选择
      this.form.selectedDevices = [];
      this.form.selectedProducts = [];
      
      if (this.form.triggerType === 'device') {
        this.form.selectedDevices = this.selectedDevices.map(device => {
          console.log('Processing device:', device);
          const deviceId = device.deviceId || device.id;
          console.log('Using device ID:', deviceId);
          return {
            ...device,
            id: deviceId,
            deviceId: deviceId
          };
        });
        console.log('Final selected devices:', this.form.selectedDevices);
      } else {
        this.form.selectedProducts = this.selectedDevices.map(product => {
          console.log('Processing product:', product);
          const productId = product.productId || product.id;
          console.log('Using product ID:', productId);
          return {
            ...product,
            id: productId,
            productId: productId
          };
        });
        console.log('Final selected products:', this.form.selectedProducts);
      }
      this.deviceDialogVisible = false;

      // 强制更新视图
      this.$nextTick(() => {
        this.$forceUpdate();
      });
    },
    // 处理物模型变化
    handleModelChange(val, index) {
      this.$set(this.form.modelConfigs, index, val);
    }
  }
};
</script> 